package com.sss.portalrimac.web.cambiocontrasena.controller;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.RenderResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.portlet.bind.annotation.ActionMapping;
import org.springframework.web.portlet.bind.annotation.RenderMapping;

import com.sss.portalrimac.application.ClienteService;
import com.sss.portalrimac.domain.command.CambioContrasenaCommand;

@Controller(value = "cambioContrasenaController")
@RequestMapping("VIEW")
public class CambioContrasenaController {

	private ClienteService clienteService;	
	
	public static final String CAMBIAR_CONTRASENA_FORM = "cambioContrasena/cambiarContrasena";
	public static final String SUCCESS_VIEW = "cambioContrasena/cambiarContrasenaSatisfactorio";
	
	public static final String PARAM_ACCION = "action";
	public static final String SUCCESS_ACTION = "vista";
	public static final String COMMAND_CLASS = "detalleCambioContrasena";
		
	
	public CambioContrasenaController(ClienteService clienteService) {
		this.clienteService = clienteService;
	}
	
	@Autowired
	@Qualifier("detalleCambioContrasenaValidator")
	private Validator detalleCambioContrasenaValidator;
	
	public void setValidator(Validator detalleCambioContrasenaValidator){
		this.detalleCambioContrasenaValidator=detalleCambioContrasenaValidator;
	}
	
	@RenderMapping
	public String cambiarContrasenaForm(RenderResponse response) {
		return CAMBIAR_CONTRASENA_FORM;
	}

	@ActionMapping(params = "action=cambiarContrasena")
	public void cambiarContrasena(@ModelAttribute(value=COMMAND_CLASS)CambioContrasenaCommand detallesCambioContrasena,BindingResult bindingResult, 
								  ActionRequest actionRequest,ActionResponse actionResponse) throws Exception{

		detalleCambioContrasenaValidator.validate(detallesCambioContrasena, bindingResult);
		if(!bindingResult.hasErrors()){
			clienteService.cambiarContrasena(actionRequest,actionResponse,detallesCambioContrasena);
			actionResponse.setRenderParameter(PARAM_ACCION, SUCCESS_ACTION);
		}
		else{
			actionResponse.setRenderParameter(PARAM_ACCION, CAMBIAR_CONTRASENA_FORM);
		}
	}
	
	@ModelAttribute(COMMAND_CLASS)                                                                                
	public CambioContrasenaCommand getCommandObject() {
	   return new CambioContrasenaCommand();
	}

	@RenderMapping(params = "action="+SUCCESS_ACTION)
	public String cambiarContrasenaSuccess(RenderResponse response) {
		return SUCCESS_VIEW;
	}
}
